//
//  ExercisesPageViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/8.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "ExercisesPageViewController.h"
#import "ExercisesContainViewController.h"
#import "ExercisesAnswerCardViewController.h"
#import "ExercisesPageSubItemView.h"
#import "ExercisesPageCoverView.h"
#import "ExercisesBackAlertView.h"
#import "ExercisesNormalAlertView.h"
#import "ExercisesPageModel.h"
#import "ExercieseQuestionItemModel.h"
@interface ExercisesPageViewController ()
@property (nonatomic,strong)UILabel * titleLb;
@property (nonatomic,strong)ExercisesPageCoverView *coverView;
@property (nonatomic,strong)ExercisesPageModel *dtlModel;
@property (nonatomic,strong)ExercisesPageModel *lastModel;
@property (nonatomic,strong)UIButton *confirmBtn;
@property (nonatomic,strong)UILabel *messageLb;
@property (nonatomic,strong)NSNumber *lessonId;
@property (nonatomic,strong)NSNumber *paperId;
@property (nonatomic,strong)CAGradientLayer *gradientLayer;
@property (nonatomic,strong)NSURLSessionTask *task;
@end

@implementation ExercisesPageViewController



- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.task cancel];

}


- (instancetype)initWithLessonId:(NSNumber *)lessonId paperId:(NSNumber *)paperId{
    if (self = [super init]) {
        self.lessonId = lessonId;
        self.paperId = paperId;
        
        self.lastModel =[ExercisesPageModel getCurrentExercieseById:paperId];

        [[NSUserDefaults standardUserDefaults]setObject:self.lessonId forKey:@"currentLessonId"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHideNavBar = [RPAppManager isShowNetworkView];
    
    if ([RPAppManager isShowNetworkView]) {
        [self setNetworkErrorUI];
    }else{
        [self setNetworkNarmalUI];
    }
    

    // Do any additional setup after loading the view.
}


- (void)setNetworkErrorUI{
    @zf_weakify(self)
    [self showNetworkErrorWithNavTitle:@"课后练习" completeBlock:^{
        @zf_strongify(self)
        [self setNetworkNarmalUI];
    } cancelBlock:^{
        @zf_strongify(self)
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
- (void)setNetworkNarmalUI{
    [self setUI];
    [self loadDataSource];
    [self updateFrame];

}

- (void)setUI{
    [self.view addSubview:self.titleLb];
    [self.view addSubview:self.coverView];
    [self.view addSubview:self.confirmBtn];
    [self.view addSubview:self.messageLb];
    
    self.titleLb.hidden = YES;
    self.coverView.hidden = YES;
    self.confirmBtn.hidden = YES;
    self.messageLb.hidden = YES;
    
    self.navigationController.navigationBar.translucent = NO;
    
    [self.confirmBtn layoutIfNeeded];
    
    [self.confirmBtn.layer insertSublayer:self.gradientLayer atIndex:0];

}

- (void)updateFrame{
    [self.titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(85);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(42);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-42);
        }else{
            make.top.equalTo(self.view).offset(85);
            make.left.equalTo(self.view).offset(42);
            make.right.equalTo(self.view).offset(-42);
        }
        make.centerX.equalTo(self.view);
    }];
    [self.coverView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.titleLb.mas_bottom).offset(30);
        make.size.mas_equalTo(CGSizeMake(200, 34));
    }];
    [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-60 + GK_SAVEAREA_BTM);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(16);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-16);
        }else{
            make.bottom.equalTo(self.view).offset(-60);
            make.left.equalTo(self.view).offset(20);
            make.right.equalTo(self.view).offset(-12);
        }
        make.height.mas_equalTo(44);
    }];
    [self.messageLb mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(16);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-16);
        }else{
            make.left.equalTo(self.view).offset(16);
            make.right.equalTo(self.view).offset(-16);
        }
        make.bottom.equalTo(self.confirmBtn.mas_top).offset(-26);
    }];
}

- (void)loadDataSource{
    
    [self showDataLoadState];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetPaperByLessonId];
    param[@"id"] = self.lessonId;
    self.task = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetPaperByLessonId) parames:param success:^(id responseObj) {
        [self hideDataLoadLoadState];
      
        self.dtlModel = [ExercisesPageModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        // 进行数据解析合并
        [self.dtlModel modifyObject];
        // 显示视图
        self.titleLb.hidden = NO;
        self.coverView.hidden = NO;
        self.confirmBtn.hidden = NO;
        self.messageLb.hidden = NO;
        // 赋值
        self.titleLb.text = self.dtlModel.name;
        self.coverView.count = self.dtlModel.questionCount.stringValue;
        // 动态添加子标题内容
        [self addSubItemView];
        
        [self loadRealmData];
        
    } failure:^(id error) {
        [self hideDataLoadLoadState];
    }];
}

- (void)back{
    if (self.isVideoFinish) {
        UIViewController *controller = self;
        while(controller.presentingViewController != nil){
            controller = controller.presentingViewController;
        }
        [controller dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)addSubItemView{
    UIView *lastView = nil;
    
    NSInteger totalScore = 0;
    
    for (ExercisesTitleModel *obj in self.dtlModel.titleItems) {
        ExercisesPageSubItemView *itemView = [[ExercisesPageSubItemView alloc]initWithItemTitle:obj.name andScore:obj.totalScore];
        [self.view addSubview:itemView];
        if (lastView == nil) {
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.view).offset(16);
                make.right.equalTo(self.view).offset(-16);
                make.top.equalTo(self.coverView.mas_bottom).offset(60);
            }];
        }else{
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.view).offset(16);
                make.right.equalTo(self.view).offset(-16);
                make.top.equalTo(lastView.mas_bottom).offset(25);
            }];
        }
        lastView = itemView;
        
        totalScore +=obj.totalScore.intValue;
    }
    self.coverView.score = [NSString stringWithFormat:@"%li",(long)totalScore];
}

- (void)loadRealmData{
    
    ExercisesContainViewController *containVC  = [[ExercisesContainViewController alloc]init];
    containVC.isVideoFinish = self.isVideoFinish;
    __weak typeof(self)weakSelf = self;
    if (self.lastModel != nil) {
        // 首先判断是否有上次记录
        ExercisesBackAlertView *alertView = [[ExercisesBackAlertView alloc]initWithConfirmAciton:^{
            containVC.dtlModel = self.lastModel;
            [weakSelf.navigationController pushViewController:containVC animated:YES];
        } cancelAction:^{
            [ExercisesPageModel deleteExercieseById:self.dtlModel.id];
            self.lastModel = nil;
//            [ExercisesPageModel deleteExercieseById:weakSelf.paperId];
//            containVC.dtlModel = weakSelf.dtlModel;
//            [weakSelf.navigationController pushViewController:containVC animated:YES];
        }];
        [alertView show];
    }
}

- (UILabel *)titleLb{
    if (!_titleLb) {
        _titleLb = [[UILabel alloc]init];
        _titleLb.textColor = RGBA(35, 24, 21, 1);
        _titleLb.font = [UIFont boldSystemFontOfSize:26];
        _titleLb.textAlignment = NSTextAlignmentCenter;
        _titleLb.numberOfLines = 2;
    }
    return _titleLb;
}

- (ExercisesPageCoverView *)coverView{
    if (!_coverView) {
        _coverView = [[ExercisesPageCoverView alloc]init];
        _coverView.layer.cornerRadius = 17;
        _coverView.layer.masksToBounds = YES;
        _coverView.backgroundColor = RGBA(86, 128, 250, 0.05);

    }
    return _coverView;
}

- (UIButton *)confirmBtn{
    if (!_confirmBtn) {
        _confirmBtn = [[UIButton alloc]init];
        [_confirmBtn setTitle:@"开始答题" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _confirmBtn.backgroundColor = [RPAppManager themColor];
        _confirmBtn.titleLabel.font = font(18);
        _confirmBtn.layer.cornerRadius = 22;
        _confirmBtn.layer.masksToBounds = YES;
        [_confirmBtn addTarget:self action:@selector(confirmMethod) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmBtn;
}
- (UILabel *)messageLb{
    if (!_messageLb) {
        _messageLb = [[UILabel alloc]init];
        _messageLb.text = @"开始答题后可以随时暂停，作答记录将同步保存";
        _messageLb.textColor = RGBA(153, 153, 153, 1);
        _messageLb.font = font(14);
        _messageLb.textAlignment = NSTextAlignmentCenter;
    }
    return _messageLb;
}

- (CAGradientLayer *)gradientLayer{
    if (!_gradientLayer) {
        _gradientLayer =  [CAGradientLayer layer];
        _gradientLayer.frame = self.confirmBtn.bounds;
        _gradientLayer.endPoint = CGPointMake(0, 0);
        _gradientLayer.startPoint  = CGPointMake(1.0, 0);
        _gradientLayer.colors = @[(id)RGBA(119, 153, 255, 1).CGColor,(id)RGBA(86, 128, 250, 1).CGColor];
    }
    return _gradientLayer;
}

#pragma mark - action
- (void)confirmMethod{
    [MobClick event:@"exercise_card_home_click"];
    ExercisesContainViewController *containVC  = [[ExercisesContainViewController alloc]init];
    containVC.isVideoFinish = self.isVideoFinish;
    containVC.dtlModel = self.dtlModel;
    [self.navigationController pushViewController:containVC animated:YES];
}
@end
